package com.itheima.tlias.filter;

import com.itheima.tlias.utils.CurrentHolder;
import com.itheima.tlias.utils.JwtUtils;
import io.jsonwebtoken.Claims;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;

import org.springframework.util.StringUtils;

//import jakarta.servlet.*;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Slf4j
//@WebFilter("/*")
public class TokenFilter implements Filter {
    /**
     * 过滤器
     *
     * @param servletRequest  请求
     * @param servletResponse 响应
     * @param filterChain     过滤器
     * @throws IOException      抛出异常
     * @throws ServletException 抛出异常
     */
    @Override
    public void doFilter(ServletRequest servletRequest,
                         ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 获取url
        String url = request.getRequestURI();
        // 放行登录请求
        if (url.contains("login")) {
            log.info("登录请求");
            filterChain.doFilter(request, response);
            return;
        }
        // 获取token
        String jwt = request.getHeader("token");
        // 判断token是否为空
        if (!StringUtils.hasLength(jwt)) {
            log.info("错误, token为空");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return;
        }
        // 解析token
        try {
          Claims claims = JwtUtils.parseJWT(jwt);
          Integer empId = Integer.valueOf(claims.get("id").toString());
          CurrentHolder.setCurrentId(empId);
          log.info("token解析成功, 放行");
        } catch (Exception e) {
            e.printStackTrace();
            log.info("错误, token解析失败");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return;
        }
        // 放行
        log.info("放行");
        filterChain.doFilter(request, response);
        // 清空当前线程绑定id
        CurrentHolder.remove();
    }
}
